package com.tdzx.ui;


import java.util.List;

import org.json.JSONException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.tdzx.R;
import com.tdzx.constant.Constant;
import com.tdzx.entity.CompanyEntity;
import com.tdzx.util.SharePrefenceUtil;
import com.tdzx.util.StringUtils;
import com.tdzx.view.MaskImage;
import com.tdzx.view.SelectPicPopupWindow;

public class FoucsActivity extends BaseActivity_NoBar {
	GridView allFocus;
	FocusAdapter fAdapter;
	
	ImageLoader imageLoader = ImageLoader.getInstance();
	
	boolean flag = false;
	
	ImageView caterory_back;
	ImageView cat_src;
	SelectPicPopupWindow menuWindow;
	
	AsyncHttpClient client;
	
	List<CompanyEntity> listCompany;
	DisplayImageOptions options;
	
	TextView btn_sm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.focus);
		
		options = new DisplayImageOptions.Builder()
		// .showImageForEmptyUri(R.drawable.ic_empty)
		// .showImageOnFail(R.drawable.ic_error)
		.resetViewBeforeLoading().cacheOnDisc()
		.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.displayer(new FadeInBitmapDisplayer(300)).build();
		
		client = new AsyncHttpClient();
		showProgress("正在加载数据...");
		//
		client.get(Constant.getAllListUserEntity, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				finishProgress();
				listCompany = CompanyEntity.getCompanyList(content);
				fAdapter.notifyDataSetChanged();
				super.onSuccess(content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				finishProgress();
				showToast("网络错误,获取数据失败");
				super.onFailure(error, content);
			}
			
		});
		
		initViewTop();
		allFocus = (GridView) findViewById(R.id.allFocus);
		fAdapter = new FocusAdapter();
		allFocus.setAdapter(fAdapter);
		
		/*allFocus.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionevent) {
				for(int i = 0; i < allFocus.getChildCount();i++) {
					View child = allFocus.getChildAt(i);
					ImageView delete = (ImageView) child.findViewById(R.id.delete);
					delete.setVisibility(View.GONE);
				}
				return false;
			}
		});*/
	}
	
	private void initViewTop() {
		caterory_back = (ImageView) findViewById(R.id.caterory_back);
		caterory_back.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Log.i("ccc", "onTouch ca");
				cat_src.onTouchEvent(arg1);
				return false;
			}
		});
		
		caterory_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		cat_src = (ImageView) findViewById(R.id.cat_src);
		cat_src.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Log.i("ccc", "onTouch crc");
				return true;
			}
		});
		
	}
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int position = msg.what;
			String userId = listCompany.get(position).getUser_Id();
			cancel(userId, position);
			super.handleMessage(msg);
		}
		
	};
	
	public void cancel(String userId,final int position) {
		showProgress("正在取消关注");
		client.get(Constant.deleteMemerbToUser + "&member_id=" + SharePrefenceUtil.getUserID(FoucsActivity.this) + "&user_id=" + userId, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				finishProgress();
				try {
					if(StringUtils.isSuccessTD(content)) {
						showToast("取消关注成功");
						listCompany.remove(position);
						fAdapter.notifyDataSetChanged();
//						allFocus.performClick();
						for(int i = 0; i < allFocus.getChildCount();i++) {
							View child = allFocus.getChildAt(i);
							ImageView delete = (ImageView) child.findViewById(R.id.delete);
							delete.setVisibility(View.GONE);
						}
					} else {
						showToast("取消关注失败");
					}
					super.onSuccess(content);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable error, String content) {
				finishProgress();
				showToast("网络错误,取消关注失败");
				super.onFailure(error, content);
			}
			
		});
	}
 

	class FocusAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return listCompany == null ? 0 : listCompany.size();
		}

		@Override
		public Object getItem(int i) {
			return listCompany.get(i);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(final int i, View view, ViewGroup viewgroup) {
			if(view == null) {
				view = View.inflate(FoucsActivity.this, R.layout.focus_item, null);
			}
			
			final MaskImage focus_img = (MaskImage) view.findViewById(R.id.focus_img);
			imageLoader.loadImage(listCompany.get(i).getUser_adver(), options, new ImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					
				}
				@Override
				public void onLoadingFailed(String imageUri, View view,
						FailReason failReason) {
					focus_img.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.app));
				}
				
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					focus_img.setBitmap(loadedImage);
				}
				
				@Override
				public void onLoadingCancelled(String imageUri, View view) {
					
				}
			});
			
			TextView comname = (TextView) view.findViewById(R.id.comname);
			comname.setText(listCompany.get(i).getUser_Name());
			
//			focus_img.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.qz1));
			final ImageView delete = (ImageView) view.findViewById(R.id.delete);
			delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					menuWindow = new SelectPicPopupWindow(FoucsActivity.this,"取消关注\"" + listCompany.get(i).getUser_Name() + "\"后将不再收到其下发的消息",i,mHandler);
	                menuWindow.showAtLocation(FoucsActivity.this.findViewById(R.id.pushAn_main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
				}
			});
			
			/*focus_img.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View view) {
					delete.setVisibility(View.VISIBLE);
					return false;
				}
			});*/
			
			focus_img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					if(!delete.isShown()) {
//						Toast.makeText(FoucsActivity.this, "跳转", Toast.LENGTH_SHORT).show();
						/*Intent intent_content = new Intent(FoucsActivity.this, MerchanContentActivity.class);
						intent_content.putExtra("merchanName", listCompany.get(i).getUser_Name());
						intent_content.putExtra("userId", listCompany.get(i).getUser_Id());
						intent_content.putExtra("userImg", listCompany.get(i).getUser_adver());
						startActivity(intent_content);*/
						
						if(SharePrefenceUtil.checkLogin(FoucsActivity.this)) {
							Intent intentDetail = new Intent(FoucsActivity.this, CompanyDetail.class);
							intentDetail.putExtra("userId", listCompany.get(i).getUser_Id());
							intentDetail.putExtra("comName", listCompany.get(i).getUser_Name());
							intentDetail.putExtra("userImg", listCompany.get(i).getUser_adver());
							startActivity(intentDetail);
						} else {
							Intent intent_login = new Intent(FoucsActivity.this, UserLogin.class);
							startActivity(intent_login);
						}
					}
				}
			});
			
			return view;
		}
	}
}
